package handlers

import (
	"brood-agent2/utils"
	"os"
	"path/filepath"
)

func InstallEtcdImpl(installer EtcdInstaller) error {

	utils.Logger.Info("install etcd begin")
	err := installCheck("etcd.service")
	if err != nil {
		return err
	}

	// 下载解压
	utils.Logger.Info("download and extract etcd")
	err = extractPkg(installer.PkgUrl.Url, installer.ApplicationDir, installer.PkgUrl.ExtractType, "etcd")
	if err != nil {
		return err
	}

	// 创建软连接
	err = addSoftLink(filepath.Join(installer.ApplicationDir, "etcd", "etcd"), "/usr/bin/etcd")
	if err != nil {
		return err
	}
	err = addSoftLink(filepath.Join(installer.ApplicationDir, "etcd", "etcdctl"), "/usr/bin/etcdctl")
	if err != nil {
		return err
	}

	// 下载所需配置
	utils.Logger.Info("download depend files")
	for _, download := range installer.DependFiles {
		err = utils.DownloadFile(download.Url, download.SavePath, os.FileMode(0755), false)
		if err != nil {
			return err
		}
	}

	err = utils.RegisterService("etcd.service")
	if err != nil {
		return err
	}

	utils.Logger.Info("add alisa for etcdctl")
	err = utils.WriteStringToFile("/root/.bashrc", "\n"+installer.EtcdctlAlisa, os.O_APPEND, os.FileMode(0755))
	if err != nil {
		return err
	}

	utils.Logger.Info("install etcd done")

	return nil
}
